package com.snails.app.glide;

import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.bumptech.glide.load.engine.cache.DiskCache;
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper;
import com.snails.net.utils.FileUtil;

import java.io.File;

/**
 * Glide本地图片缓存
 * @author lawrence
 * @date 2019-05-15 18:04
 */
public final class SnailsGlideCacheFactory implements DiskCache.Factory {
    public interface CacheDirectoryGetter { File getCacheDirectory(); }

    private final long diskCacheSize;
    private final CacheDirectoryGetter cacheDirectoryGetter;

    public SnailsGlideCacheFactory(Context appCtx) {
        this(appCtx, "", DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE);
    }

    public SnailsGlideCacheFactory(Context appCtx, String folderName, long diskCacheSize) {
        this(new SnailsCacheDirectoryGetter(appCtx, folderName), diskCacheSize);
    }

    public SnailsGlideCacheFactory(CacheDirectoryGetter cacheDirectoryGetter, long diskCacheSize) {
        this.diskCacheSize = diskCacheSize;
        this.cacheDirectoryGetter = cacheDirectoryGetter;
    }

    /**
     * 得到file地址
     */
    @Nullable public String getFolder() {
        final File file = cacheDirectoryGetter != null ?
                cacheDirectoryGetter.getCacheDirectory() : null;
        return file != null ? file.getAbsolutePath() : null;
    }

    @Nullable
    @Override
    public DiskCache build() {
        File cacheDir = cacheDirectoryGetter.getCacheDirectory();

        if (cacheDir == null) {
            return null;
        }

        if (!cacheDir.mkdirs() && (!cacheDir.exists() || !cacheDir.isDirectory())) {
            return null;
        }

        return DiskLruCacheWrapper.create(cacheDir, diskCacheSize);
    }

    public static final class SnailsCacheDirectoryGetter implements CacheDirectoryGetter {

        private final File cache;


        public SnailsCacheDirectoryGetter(Context appCtx, String folderName) {
            folderName = TextUtils.isEmpty(folderName) ?
                    DiskCache.Factory.DEFAULT_DISK_CACHE_DIR : folderName;
            File file = FileUtil.appCreateCache(appCtx, folderName);
            if (file == null) {
                file = appCtx.getCacheDir();
                if (file != null) file = new File(file, folderName);
            }
            cache = file;
        }

        @Override
        public File getCacheDirectory() {
            return cache;
        }

    }

}
